package com.cuput.partybuilding.publiclibrary.util;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

import com.github.promeg.pinyinhelper.Pinyin;

/**
 * Created by wei on 2017-05-10.
 */

public class Utils {
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        if (listView == null) {
            return;
        }

        //获得adapter
        ListAdapter adapter =  listView.getAdapter();
        if (adapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < adapter.getCount(); i++) {
            View listItem = adapter.getView(i, null, listView);
            listItem.measure(0, 0);
            //计算总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        //计算分割线高度
        params.height = totalHeight + (listView.getDividerHeight() * (adapter.getCount() - 1));
        //给listview设置高度
        listView.setLayoutParams(params);
    }

    public static int px2dp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 汉字的拼音首字母
     * @param chinese
     * @return
     */
    public static String getPinYin(String chinese) {
        if (chinese == null) {
            return "";
        }

        StringBuffer sb = new StringBuffer();

        sb.setLength(0);
        char[] chars = chinese.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            String temp = String.valueOf(Pinyin.toPinyin(chars[i]).charAt(0));
            sb.append(temp);
        }

        return sb.toString();
    }
}
